package cn.com.taiji.pos.controller;

import cn.com.taiji.pos.entity.AppVersion;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/app")
@Slf4j
public class AppController {

    @RequestMapping("checkVersion")
    public AppVersion checkVersion() {
        return new AppVersion();
    }

    /**
     * 上传pos双屏app文件
     *
     * @param appVersion app上传信息
     * @return 上传结果
     */
    @PostMapping("/uploadApp")
    public String uploadApp(AppVersion appVersion) {
        MultipartFile app = appVersion.getApp();
        Map<String, Object> resultMap = new HashMap();
        resultMap.put("result", "fail");
        try {
            if (app.isEmpty()) {
                resultMap.put("message", "文件为空");
            } else {
                // 获取文件名
                String appName = app.getOriginalFilename();
                log.info("上传的app名为：" + appName);
                assert appName != null;
                if (!appName.endsWith(".apk")) {
                    resultMap.put("message", "不支持的文件类型");
                } else {
                    String appPath = ResourceUtils.getURL("classpath:").getPath() + "/vue/app/" + appName;
                    File newApp = new File(new File(appPath).getAbsolutePath());
                    if (!newApp.getParentFile().exists()) {
                        newApp.getParentFile().mkdirs();
                    }
                    app.transferTo(newApp);
                    resultMap.put("result", "success");
                    resultMap.put("message", "上传成功");
                    log.info("上传的app路径：" + newApp.getAbsolutePath());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("message", "上传失败");
        }
        return JSONObject.toJSONString(resultMap);
    }

}
